<template>
  <div class="job-list-page">
    <div class="container">
      <!-- 搜索区域 -->
      <section class="search-section">
        <div class="search-bar">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="搜索职位名称、公司或技能" 
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
        
        <!-- 筛选条件 -->
        <div class="filter-section">
          <!-- 工作地点 -->
          <div class="filter-group">
            <div class="filter-label">工作地点</div>
            <div class="filter-content">
              <el-radio-group v-model="searchForm.location" size="small" @change="handleSearch">
                <el-radio-button label="">全部</el-radio-button>
                <el-radio-button v-for="city in cityOptions" :key="city" :label="city">
                  {{ city }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>
          
          <!-- 职位类型 -->
          <div class="filter-group">
            <div class="filter-label">职位类型</div>
            <div class="filter-content">
              <el-radio-group v-model="searchForm.jobType" size="small" @change="handleSearch">
                <el-radio label="">全部</el-radio>
                <el-radio label="1">全职</el-radio>
                <el-radio label="2">兼职</el-radio>
                <el-radio label="3">实习</el-radio>
              </el-radio-group>
            </div>
          </div>
          
        
          
        
        </div>
      </section>
      
      <!-- 职位列表 -->
      <section class="job-list-section">
        <!-- 排序和结果统计 -->
        <div class="list-header">
          <div class="result-stats">
            找到 <span class="stats-highlight">{{ jobs.length }}</span> 个职位
            <span v-if="jobs.length !== total" class="stats-note">(API返回总数: {{ total }})</span>
          </div>
          <div class="sort-options">
            <span class="sort-label">排序：</span>
            <el-radio-group v-model="searchForm.sort" size="small" @change="handleSearch">
              <el-radio-button label="latest">最新发布</el-radio-button>
              <el-radio-button label="salary">薪资最高</el-radio-button>
              <el-radio-button label="popular">最热门</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <!-- 职位卡片列表 -->
        <div v-if="jobs.length > 0" class="job-list">
          <job-card 
            v-for="job in jobs" 
            :key="job.id" 
            :job="job"
            class="job-item"
          />
        </div>
        
        <!-- 无数据 -->
        <el-empty 
          v-else 
          description="暂无符合条件的职位" 
          :image-size="200"
        >
          <template #extra>
            <el-button type="primary" @click="resetSearch">清除筛选条件</el-button>
          </template>
        </el-empty>
        
        <!-- 分页 -->
        <div class="pagination-container" v-if="jobs.length > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Math.max(jobs.length, total)"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getJobs, searchJobs } from '@/api/job'
import JobCard from '@/components/job/JobCard.vue'

const route = useRoute()
const router = useRouter()

// 城市选项
const cityOptions = ref(['北京', '上海', '广州', '深圳', '杭州'])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  location: '',
  jobType: '',
  education: '',
  experience: '',
  salary: '',
  time: '',
  sort: 'latest'
})

// 职位列表数据
const jobs = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 获取职位列表
const fetchJobs = async () => {
  loading.value = true
  
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchForm.keyword,
      city: searchForm.location,
      categoryId: searchForm.jobType ? parseInt(searchForm.jobType) : undefined,
      status: 1  // 明确指定只显示已审核通过的职位
    }
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (!params[key] && params[key] !== 0) delete params[key]
    })
    
    console.log('发送职位搜索请求，参数:', params)
    
    // 调用搜索接口
    const response = await searchJobs(params)
    console.log('职位搜索响应:', response)
    
    if (response && response.data) {
      jobs.value = response.data.records || []
      total.value = response.data.total || 0
      
      // 检查数据一致性并记录日志
      if (jobs.value.length === 0 && total.value > 0) {
        console.warn(`数据不一致: API返回total为${total.value}但records为空数组，可能是后端公司名称过滤导致`)
        console.warn('如果您搜索的关键词与公司名相关，这可能是由于后端的内存过滤造成的')
        console.warn('我们已经在后端修复了这个问题，修复将在下次部署后生效')
        ElMessage({
          message: '搜索结果可能不完整，建议尝试更精确的关键词',
          type: 'warning',
          duration: 5000
        })
      }
      
      // 分析响应数据
      console.log(`搜索结果统计: 找到${jobs.value.length}条记录，API返回总数: ${total.value}`)
      
      // 如果没有数据且不是第一页，则跳转到第一页
      if (jobs.value.length === 0 && currentPage.value !== 1) {
        console.log('当前页无数据，跳转到第一页')
        currentPage.value = 1
        await fetchJobs()
      }
    } else {
      console.error('职位搜索响应格式异常:', response)
      jobs.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取职位列表失败，请稍后再试')
    console.error('获取职位列表失败', error)
    jobs.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.query,
  (newQuery) => {
    // 从URL参数更新搜索条件
    if (newQuery.keyword) searchForm.keyword = newQuery.keyword
    if (newQuery.location) searchForm.location = newQuery.location
    if (newQuery.page) currentPage.value = Number(newQuery.page)
    
    // 获取职位列表
    fetchJobs()
  },
  { immediate: true }
)

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  
  // 更新URL参数
  const query = {}
  if (searchForm.keyword) query.keyword = searchForm.keyword
  if (searchForm.location) query.location = searchForm.location
  
  router.push({ path: '/jobs', query })
  
  fetchJobs()
}

// 重置搜索条件
const resetSearch = () => {
  // 重置搜索表单
  Object.keys(searchForm).forEach(key => {
    if (key !== 'sort') searchForm[key] = ''
  })
  
  currentPage.value = 1
  
  // 清除URL参数
  router.push({ path: '/jobs' })
  
  fetchJobs()
}

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchJobs()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  
  // 更新URL参数
  const query = { ...route.query, page }
  router.push({ path: '/jobs', query })
  
  fetchJobs()
}

// 页面挂载时获取数据
onMounted(() => {
  // 从URL参数初始化搜索条件
  const { keyword, location, page } = route.query
  
  if (keyword) searchForm.keyword = keyword
  if (location) searchForm.location = location
  if (page) currentPage.value = Number(page)
  
  fetchJobs()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.job-list-page {
  padding: var(--spacing-xl) 0;
}

// 搜索区域
.search-section {
  margin-bottom: var(--spacing-xl);
  
  .search-bar {
    display: flex;
    margin-bottom: var(--spacing-lg);
    
    .search-input {
      flex: 1;
      margin-right: var(--spacing-sm);
    }
  }
}

// 筛选条件
.filter-section {
  background-color: #fff;
  padding: var(--spacing-lg);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

.filter-group {
  display: flex;
  border-bottom: 1px solid var(--border-color);
  padding: var(--spacing-sm) 0;
  margin-bottom: var(--spacing-sm);
  
  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
  
  .filter-label {
    width: 80px;
    color: var(--text-secondary);
    font-weight: 500;
    flex-shrink: 0;
    line-height: 32px;
  }
  
  .filter-content {
    flex: 1;
  }
}

// 职位列表区域
.job-list-section {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-lg);
    
    .result-stats {
      color: var(--text-secondary);
      
      .stats-highlight {
        color: var(--primary-color);
        font-weight: 600;
      }
      
      .stats-note {
        color: var(--text-secondary);
        font-size: 0.8em;
        margin-left: var(--spacing-sm);
        opacity: 0.8;
        font-style: italic;
      }
    }
    
    .sort-options {
      display: flex;
      align-items: center;
      
      .sort-label {
        margin-right: var(--spacing-sm);
        color: var(--text-secondary);
      }
    }
  }
  
  .job-list {
    margin-bottom: var(--spacing-xl);
  }
  
  .job-item {
    margin-bottom: var(--spacing-md);
  }
}

// 分页
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-xl);
}

// 响应式适配
@media (max-width: 768px) {
  .filter-group {
    flex-direction: column;
    
    .filter-label {
      width: 100%;
      margin-bottom: var(--spacing-xs);
    }
  }
  
  .list-header {
    flex-direction: column;
    align-items: flex-start;
    
    .result-stats {
      margin-bottom: var(--spacing-sm);
    }
  }
}
</style> 